package com.beardedcoder.lowPower.views;

import com.beardedcoder.lowPower.R;
import com.beardedcoder.lowPower.model.HomeScreenCellData;
import com.beardedcoder.utils.power.PowerFeatures;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

public class HomeScreenView extends LinearLayout {
	private HomeScreenCellData data;
	private ImageView icon;
	private TextView description;
	private ToggleButton switcher;
	private TextView info;
	private PowerFeatures feature;

	/**
	 * this constructor is called when defining this class in an XML file
	 * the attributes passed through are the XML tags inside
	 * If you plan to construct one of these view's through XML and 
	 * you have some custom XML tags defined then here is where 
	 * you can parse them into the setup. 
	 * the call through to super will handle any of the standard Android tags. 
	 * @param context
	 * @param attrs
	 */
	public HomeScreenView(Context context, AttributeSet attrs) {
		super(context, attrs);
		loadViews();
	}

	/**
	 * 
	 * @param context
	 */
	public HomeScreenView(Context context) {
		super(context);
		loadViews();
	}

	private void loadViews() {
		LayoutInflater.from(getContext()).inflate(R.layout.home_screen_cell, this);
		icon = (ImageView) findViewById(R.id.home_screen_cell_icon);
		description = (TextView) findViewById(R.id.home_screen_cell_title);
		info = (TextView) findViewById(R.id.home_screen_cell_info);
		switcher = (ToggleButton) findViewById(R.id.home_screen_cell_state_switcher);
		switcher.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (feature != null) {
					if (isChecked) {
						switcher.setText("On");
						feature.activate();
					} else {
						switcher.setText("Off");
						feature.deactivate();
					}
				}
			}
		});
	}
	
	public HomeScreenCellData getData() {
		return data;
	}
	
	public void setPowerFeature(PowerFeatures feature) {
		this.feature = feature;
		
		if (feature == null) {
			// unknown state
			switcher.setChecked(false);
			switcher.setEnabled(false);
		} else {
			try {
				switcher.setEnabled(true);
				switcher.setChecked(feature.isActive());
			} catch (Exception e) {
				switcher.setEnabled(false);
				e.printStackTrace();
			}			
		}
	}

	public void setData(HomeScreenCellData data) {
		icon.setImageResource(data.iconId);
		
		if (data.description != null) {
			description.setText(data.description);			
		} else {
			description.setText(data.descriptionId);			
		}
	}
}
